package com.example.netcomponent.net.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zengxianghui900 on 17/10/11.
 * APP内文件操作工具类
 *
 */

public class FileUtils {

    public static final  String APP_FILE = "claimppt";
    private static final String OFFLINE_PIC_ALBUM = "offlinePic";
    private static final String ONLINE_PIC_ALBUM = "onlinePic";
    private static final String ATTACH_SHARE = "attach";

    private static final String ONLINE_UNCLASSIFY_PIC_ALBUM = "unclassifyPic";
    private static final String BASE_DATA = "baseData";
    public static final String BANK_NORMAL = "normalBank.pa";
    public static final String PROVINCE_TYPE = "province.pa";
    public static final String COUNTRIES_DATA = "countries.pa";

    /**
     * 待勘案件列表
     **/
    public final static String WAITSURVEY_LISTDATA= "waitSurveyListData";
    /**
     * 未决管理列表
     **/
    public final static String PEND_MANAGE= "pendManage";
    /**
     * 我的名片分享生成的图片
     **/
    public final static String ME_VCARD_SHARE= "meVcardShare";


    /**
     * 写入文件
     *
     * @param in
     * @param file
     */
    public static void writeFile(InputStream in, File file) throws IOException {
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();

        if (file != null && file.exists())
            file.delete();

        FileOutputStream out = new FileOutputStream(file);
        byte[] buffer = new byte[1024 * 128];
        int len = -1;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();

    }

    /**
     * 获取apk文件保存路径
     * @return
     */
    public static File getApkSaveFile(String fileName) {
        File file = new File(Environment.getExternalStorageDirectory(), fileName);
        if (file.exists()){
            file.delete();
        }
        return file;
    }

    /**
     * 将bitmap保存为jpg图片并存储到文件中
     * @param bitmap
     * @param file
     * @throws IOException
     */
    public static void saveBitmapToJPG(Bitmap bitmap, File file) {
        OutputStream stream = null;
        try {
            stream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        try {
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * zxh 将图片保存到sd卡中
     * @param data
     * @return
     */
    public static File saveToSdCard(byte[] data,File file) {
        FileOutputStream out = null;

		/* 保存图片到sd卡中 */
        try {
            // 保存图片
            out = new FileOutputStream(file);
            out.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 获取人脸照片保存路径
     * @param type
     * @return
     */
    public static File getFaceFile(String type) {
        File folderFile = new File(Environment.getExternalStorageDirectory(), APP_FILE);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }

        if ("0".equals(type)){
            return new File(folderFile,"collect.jpg");
        }else{
            return new File(folderFile,"verify.jpg");
        }
    }

    /**
     * 获取离线相册文件夹目录
     * @return
     */
    public static File getOfflinePicAlbum(){
        File file = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + OFFLINE_PIC_ALBUM);
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取报案号文件夹根目录
     * @param reportNo
     * @return
     */
    public static File getReportNoFolder(String reportNo) {
        File file = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + reportNo);
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取报案号下照片文件夹
     * @param reportNo
     * @param isUnclassify
     * @return
     */
    public static File getOnlinePicAlbum(String reportNo, boolean isUnclassify) {
        File file;
        if (isUnclassify){      //未分类，返回未分类相册文件夹
            file = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + reportNo + File.separator + ONLINE_UNCLASSIFY_PIC_ALBUM);
        }else {
            file = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + reportNo + File.separator + ONLINE_PIC_ALBUM);
        }
        if (!file.exists()){
            file.mkdirs();
        }
        return file;
    }

    /**
     * 获取指定文件夹下，所有的文件
     * 注意：该文件夹下不能有其它文件夹
     * @param folderFile  文件夹
     * @return
     */
    public static List<String> getFolderAllFileNames(File folderFile){
        ArrayList<String> arrayList = new ArrayList<>();
        if (folderFile.exists()){
            File[] files = folderFile.listFiles();
            if(!(files==null)){
                for (File file : files) {
                    arrayList.add(file.getAbsolutePath());
                }
            }
        }
        return arrayList;
    }
    /**
     * 获取待勘列表文件目录
     *
     * @param um
     * @return
     */
    public static String getWaitSurveyListData(String um) {
        String sdcard = Environment.getExternalStorageDirectory().toString();
        File file2 = new File(sdcard + "/" + APP_FILE + "/" + WAITSURVEY_LISTDATA + "/");
        if (!file2.exists())
            file2.mkdirs();

        return sdcard + "/" + APP_FILE + "/" + WAITSURVEY_LISTDATA + "/" + um + ".pa";
    }

    /**
     * 获取未决管理缓存文件
     * @param userId
     * @param taskKey
     * @return
     */
    public static String getPendManageList(String userId, String taskKey) {

        String sdcard = Environment.getExternalStorageDirectory().toString();
        File file2 = new File(sdcard + "/" + APP_FILE + "/" + PEND_MANAGE + "/" + userId);
        if (!file2.exists()){
            file2.mkdirs();
        }
        return file2.getAbsolutePath()  + "/" + taskKey +".pa";

    }


    /**
     * 我的名片分享生成的图片
     */
    public static String getMeVcardShareImg() {
        String sdcard = Environment.getExternalStorageDirectory().toString();
        File file2 = new File(sdcard + "/" + APP_FILE + "/" + ME_VCARD_SHARE + "/");
        if (!file2.exists())
            file2.mkdirs();

        return sdcard + "/" + APP_FILE + "/" + ME_VCARD_SHARE;

    }
    /**
     * 保存文件
     *
     * @param jsonData
     * @param filePath
     */
    public static boolean saveFile(String jsonData, String filePath) {

        try {
            FileOutputStream out = new FileOutputStream(new File(filePath));
            out.write(jsonData.getBytes());
            out.close();
            return true;
        } catch (Exception e) {
            LogUtils.saveLogToSD(LogUtils.ERROR, LogUtils.getExceptionAllinformation(e));
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 保存图片在本地
     */
    public static void saveImgFile(Bitmap bm, String fileName) throws IOException {
        String subForder = getMeVcardShareImg();
        File foder = new File(subForder);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(subForder, fileName);
        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(myCaptureFile);
        bm.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 根据路径获取文件
     *
     * @param filePath
     * @return
     */
    public static String getFile(String filePath) {

        FileInputStream is = null;
        if (filePath != null && !"".equals(filePath)) {
            try {
                is = new FileInputStream(new File(filePath));
                return readFile(is);
            } catch (IOException e) {
                return null;
            } finally {
                if (is != null)
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }

        return null;
    }

    private static String readFile(FileInputStream inputStream) {
        StringBuffer readedStr = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String tmp;
            while ((tmp = br.readLine()) != null) {
                readedStr.append(tmp);
            }
            System.gc();

        } catch (UnsupportedEncodingException e) {
            return null;
        } catch (IOException e) {
            return null;
        } finally {
            try {
                if (br != null)
                    br.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return readedStr.toString();
    }

    public Object readData(String filepath, Class ob) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(filepath);
            Object o = null;
            if (file.exists()) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(filepath);
                    o = new Gson().fromJson(readFile(fis), ob);// String to
                    // class
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    try {
                        if (fis != null)
                            fis.close();
                        file.delete(); // 转换异常
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } finally {
                    try {
                        if (fis != null)
                            fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return o;
        } else {
            // Toast.makeText(context, "存储卡不存在,请检查存储卡",
            // Toast.LENGTH_LONG).show();
            return null;
        }

    }


    /**
     * 将图片复制到在线图片文件夹中
     * @param imagePath
     * @param onlinePicAlbum
     */
    public static boolean moveFiles(String imagePath, File onlinePicAlbum) {
            File file = new File(imagePath);
            if (file.exists()){
                FileInputStream inputStream = null;
                FileOutputStream outputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    byte[] data = new byte[1024];
                    //输出流
                    outputStream =new FileOutputStream(new File(onlinePicAlbum,file.getName()));
                    //开始处理流
                    while (inputStream.read(data) != -1) {
                        outputStream.write(data);
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return false;
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }finally {
                    if (inputStream!= null){
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (outputStream != null){
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }else{
                return false;
            }
        return true;
    }

    /**
     * 删除文件
     * @param imagePath
     */
    public static boolean deleteAllFile(String imagePath) {
            File file = new File(imagePath);
            if (file.exists()){
                file.delete();
            }else{
                return false;
            }
        return true;
    }

    /**
     * 获取基础数据缓存文件
     * @param fileName
     * @return
     */
    public static File getBaseDataFile(String fileName){
        File folderFile = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + BASE_DATA);
        if (!folderFile.exists()){
            folderFile.mkdirs();
        }
        return new File(folderFile,fileName);
    }

    /**
     * 获取根目录下指定文件名文件
     * @param fileName
     * @return
     */
    public static File getRootFile(String fileName){
        File folderFile = new File(Environment.getExternalStorageDirectory(), APP_FILE);
        if (!folderFile.exists()){
            folderFile.mkdirs();
        }
        return new File(folderFile,fileName);
    }

    /**
     * 分享附件是否存在,且是最新的
     * @param fileName
     * @param createdDate
     * @return
     */
    public static boolean isDownloadAttachFile(String fileName, long createdDate) {
        File folder = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + ATTACH_SHARE);
        File file = new File(folder,fileName);
        if (!file.exists()){
            return false;
        }else{
            if (file.lastModified() > createdDate){
                //表明已经是最新的
                return true;
            }else{
                return false;
            }

        }
    }

    /**
     * 获取分享附件file
     * @param fileName
     * @return
     */
    public static File getAttachShareFile(String fileName) {
        File folder = new File(Environment.getExternalStorageDirectory(), APP_FILE + File.separator + ATTACH_SHARE);
        File file = new File(folder,fileName);
        return file;
    }


    /**
     * 根据图片uri获取其绝对路径
     * @param context
     * @param uri
     * @return
     */
    public static String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
